package com.cloudweb.oa.controller.mobile;

import cn.js.fan.db.ResultIterator;
import cn.js.fan.db.ResultRecord;
import cn.js.fan.db.SQLFilter;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.ErrMsgException;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.cloudweb.oa.api.IAttendanceService;
import com.cloudweb.oa.cache.UserCache;
import com.cloudweb.oa.entity.DeptUser;
import com.cloudweb.oa.entity.Role;
import com.cloudweb.oa.entity.User;
import com.cloudweb.oa.security.AuthUtil;
import com.cloudweb.oa.service.HomeService;
import com.cloudweb.oa.service.IUserService;
import com.cloudweb.oa.service.LeaveBalanceService;
import com.cloudweb.oa.vo.Result;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.attendance.ShiftScheduleMgr;
import com.redmoon.oa.flow.FormDb;
import com.redmoon.oa.visual.FormDAO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.*;

@Api(tags = "手机端打卡")
@Controller
public class MobileHrController {

    @Autowired
    HomeService homeService;

    @Autowired
    AuthUtil authUtil;

    @Autowired
    UserCache userCache;

    @Autowired
    HttpServletRequest request;

    @Autowired
    LeaveBalanceService leaveBalanceService;

    @Autowired
    IUserService userService;

    @Autowired
    IAttendanceService attendanceService;

    @ApiOperation(value = "打卡页面", notes = "打卡页面", httpMethod = "POST")
    @ResponseBody
    @RequestMapping(value = "/m/hr/punchPage")
    public Result<Object> punchPage() throws SQLException {
        return new Result<>(attendanceService.getPunchPage());
    }

    @ApiOperation(value = "打卡", notes = "打卡", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lng", value = "经度", required = true, dataType = "Double"),
            @ApiImplicitParam(name = "lat", value = "纬度", required = true, dataType = "Double"),
            @ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer"),
    })
    @ResponseBody
    @RequestMapping(value = "/m/hr/punch", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> punch(HttpServletRequest request /*@RequestParam Double lng, @RequestParam Double lat, @RequestParam(required = false) String address, @RequestParam Integer type, @RequestParam(value = "files") MultipartFile[] files*/) {
        String userName = authUtil.getUserName();

        int photoCount = 0;
        Object[] ary = ShiftScheduleMgr.getShiftDAO(userName, new Date());
        FormDAO fdao = (FormDAO) ary[0];
        if (fdao != null) {
            photoCount = StrUtil.toInt(fdao.getFieldValue("photo_count"), 0);
        }

        double lat, lng;
        String address;
        int type;
        MultipartFile[] files;
        if (photoCount > 0) {
            // 多图上传
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            if (!multipartResolver.isMultipart(request)) {
                return new Result<>(false, "上传格式非法");
            }

            MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(request);
            lat = ParamUtil.getDouble(multiRequest, "lat");
            lng = ParamUtil.getDouble(multiRequest, "lng");
            address = ParamUtil.get(multiRequest, "address");
            type = ParamUtil.getInt(multiRequest, "type");

            files = new MultipartFile[multiRequest.getFileMap().size()];
            Iterator<String> names = multiRequest.getFileNames();
            int i = 0;
            while (names.hasNext()) {
                MultipartFile file = multiRequest.getFile(names.next());
                if (file != null) {
                    files[i] = file;
                    i++;
                }
            }
        } else {
            lat = ParamUtil.getDouble(request, "lat");
            lng = ParamUtil.getDouble(request, "lng");
            address = ParamUtil.get(request, "address");
            type = ParamUtil.getInt(request, "type");
            files = new MultipartFile[0];
        }

        long[] r;
        try {
            r = attendanceService.punch(authUtil.getUserName(), lat, lng, address, type, files);
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }

        if (r[0] != -1) {
            com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
            json.put("result", r[0]);
            json.put("min", r[1]);
            json.put("id", r[2]); // 打卡記錄的ID
            return new Result<>(json);
        } else {
            return new Result<>(false);
        }
    }

    @ApiOperation(value = "报告原因", notes = "报告原因", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "remark", value = "原因", required = true, dataType = "String"),
    })
    @ResponseBody
    @RequestMapping(value = "/m/hr/punchRemark", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> punchRemark(@RequestParam Long id, @RequestParam String remark) {
        try {
            FormDb fd = new FormDb();
            fd = fd.getFormDb("kaoqin_time_sign");
            FormDAO fdao = new FormDAO();
            fdao = fdao.getFormDAOByCache(id, fd);
            fdao.setFieldValue("remark", remark);
            fdao.save();
        } catch (ErrMsgException e) {
            return new Result<>(false, e.getMessage());
        }
        return new Result<>();
    }

    @ApiOperation(value = "离岗", notes = "离岗", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "remark", value = "原因", required = true, dataType = "String"),
    })
    @ResponseBody
    @RequestMapping(value = "/m/hr/onDuty", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"})
    public Result<Object> onDuty(@RequestParam Boolean isOnDuty, @RequestParam(required = false) String remark) {
        User user = userCache.getUser(authUtil.getUserName());
        user.setRemark(remark);
        user.setOnDuty(isOnDuty);
        return new Result<>(userService.updateByUserName(user));
    }
}
